package hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class threeSum2 {
    public List<List<Integer>> threeSum(int[] nums) {
        //排序 + 双指针
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2;i++) {
            int left = i + 1;
            int right = nums.length - 1;
            if (nums[i] > 0) {
                break;
            }
            while (left < right) {
                if (nums[i] + nums[left] + nums[right] == 0) {
                    List<Integer> tem = new ArrayList<>();
                    tem.add(nums[i]);
                    tem.add(nums[left]);
                    tem.add(nums[right]);
                    ret.add(tem);
                    //去重
                    while (left < right && nums[left + 1] == nums[left]) {
                        left++;
                    }
                    while (left < right && nums[right - 1] == nums[right]) {
                        right--;
                    }
                    left++;
                    right--;

                } else if (nums[i] + nums[left] + nums[right] > 0) {
                    right--;
                } else {
                    left++;
                }
            }

            while (i < nums.length - 2 && nums[i + 1] == nums[i]) {
                i++;
            }

        }

        return ret;
    }
}
